const pool = require('../config/db');
const bcrypt = require('bcryptjs');

const userController = {
    // 用户注册
    // 用户注册
    register: async (req, res) => {
        const connection = await pool.getConnection();
        try {
            await connection.beginTransaction();

            const { username, password, email } = req.body;
            
            // 检查用户名是否已存在
            const [existingUsers] = await connection.query(
                'SELECT id FROM users WHERE username = ?',
                [username]
            );

            if (existingUsers.length > 0) {
                return res.status(400).json({ error: '用户名已存在' });
            }

            // 加密密码
            const hashedPassword = await bcrypt.hash(password, 10);

            // 创建用户
            const [userResult] = await connection.query(
                'INSERT INTO users (username, password, email) VALUES (?, ?, ?)',
                [username, hashedPassword, email]
            );

            const userId = userResult.insertId;

            // 创建默认文件夹
            const defaultFolders = [
                '我的文档',
                '我的图片',
                '我的视频',
                '我的音乐'
            ];

            for (const folderName of defaultFolders) {
                await connection.query(
                    'INSERT INTO folders (folder_name, parent_id, user_id) VALUES (?, NULL, ?)',
                    [folderName, userId]
                );
            }

            await connection.commit();

            res.json({
                success: true,
                userId,
                message: '用户注册成功，默认文件夹已创建'
            });
        } catch (error) {
            await connection.rollback();
            res.status(500).json({ error: '注册失败', details: error.message });
        } finally {
            connection.release();
        }
    },

    // 用户登录
    login: async (req, res) => {
        try {
            const { username, password } = req.body;
            
            // 查询用户
            const [users] = await pool.promise().execute(
                'SELECT * FROM users WHERE username = ?',
                [username]
            );
            
            if (users.length === 0) {
                return res.status(401).json({ error: '用户名或密码错误' });
            }
            
            const user = users[0];
            
            // 验证密码
            const isValidPassword = await bcrypt.compare(password, user.password);
            if (!isValidPassword) {
                return res.status(401).json({ error: '用户名或密码错误' });
            }
            
            // 返回用户信息（不包含密码）
            const { password: _, ...userInfo } = user;
            res.json({
                success: true,
                user: userInfo,
                message: '登录成功'
            });
        } catch (error) {
            res.status(500).json({ error: '登录失败' });
        }
    },

    // 获取用户信息
    getUserInfo: async (req, res) => {
        try {
            const userId = req.params.userId;
            const [users] = await pool.promise().execute(
                'SELECT id, username, email, created_at FROM users WHERE id = ?',
                [userId]
            );
            
            if (users.length === 0) {
                return res.status(404).json({ error: '用户不存在' });
            }
            
            res.json(users[0]);
        } catch (error) {
            res.status(500).json({ error: '获取用户信息失败' });
        }
    },

    // 更新用户信息
    updateUser: async (req, res) => {
        try {
            const userId = req.params.userId;
            const { email } = req.body;
            
            const query = 'UPDATE users SET email = ? WHERE id = ?';
            await pool.promise().execute(query, [email, userId]);
            
            res.json({ success: true, message: '用户信息更新成功' });
        } catch (error) {
            res.status(500).json({ error: '更新用户信息失败' });
        }
    },

    // 修改密码
    changePassword: async (req, res) => {
        try {
            const userId = req.params.userId;
            const { oldPassword, newPassword } = req.body;
            
            // 获取用户当前密码
            const [users] = await pool.promise().execute(
                'SELECT password FROM users WHERE id = ?',
                [userId]
            );
            
            if (users.length === 0) {
                return res.status(404).json({ error: '用户不存在' });
            }
            
            // 验证旧密码
            const isValidPassword = await bcrypt.compare(oldPassword, users[0].password);
            if (!isValidPassword) {
                return res.status(401).json({ error: '原密码错误' });
            }
            
            // 加密新密码
            const hashedPassword = await bcrypt.hash(newPassword, 10);
            
            // 更新密码
            await pool.promise().execute(
                'UPDATE users SET password = ? WHERE id = ?',
                [hashedPassword, userId]
            );
            
            res.json({ success: true, message: '密码修改成功' });
        } catch (error) {
            res.status(500).json({ error: '修改密码失败' });
        }
    },

    // 删除用户
    deleteUser: async (req, res) => {
        try {
            const userId = req.params.userId;
            
            // 删除用户相关的文件和分享记录
            await pool.promise().execute('DELETE FROM shared_files WHERE shared_by = ? OR shared_with = ?', [userId, userId]);
            await pool.promise().execute('DELETE FROM files WHERE user_id = ?', [userId]);
            await pool.promise().execute('DELETE FROM users WHERE id = ?', [userId]);
            
            res.json({ success: true, message: '用户删除成功' });
        } catch (error) {
            res.status(500).json({ error: '删除用户失败' });
        }
    }
};

module.exports = userController;